import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  Image,
  StyleSheet,
  ScrollView,
  ActivityIndicator,
  Alert,
  Platform,
} from 'react-native';
import { useRouter } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import { StatusBar } from 'expo-status-bar';
import * as ImagePicker from 'expo-image-picker';
import { Ionicons } from '@expo/vector-icons';
import { createPostWithImages } from '../services/postService';

// 预定义标签
const TAGS = [
  '校园生活',
  '学术研究',
  '社团活动',
  '职业发展',
  '资源分享',
  '校友交流',
];

// 定义API响应类型
interface ApiResponse {
  code: number;
  data: any;
  message: string;
}

export default function CreatePostScreen() {
  const router = useRouter();
  const [content, setContent] = useState('');
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [images, setImages] = useState<ImagePicker.ImagePickerAsset[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  // 处理图片选择
  const pickImage = async () => {
    // 请求媒体库权限
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    
    if (status !== 'granted') {
      Alert.alert('权限被拒绝', '需要访问相册权限才能选择图片');
      return;
    }
    
    // 允许用户选择多张图片
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      allowsEditing: false,
      quality: 0.8,
      allowsMultipleSelection: true,
      selectionLimit: 9, // 最多选择9张图片
    });
    
    if (!result.canceled) {
      // 检查图片数量限制
      if (images.length + result.assets.length > 9) {
        Alert.alert('图片数量超出限制', '最多只能上传9张图片');
        return;
      }
      
      // 添加新选择的图片
      setImages([...images, ...result.assets]);
    }
  };
  
  // 删除选择的图片
  const removeImage = (index: number) => {
    const updatedImages = [...images];
    updatedImages.splice(index, 1);
    setImages(updatedImages);
  };
  
  // 切换标签选择
  const toggleTag = (tag: string) => {
    if (selectedTags.includes(tag)) {
      setSelectedTags(selectedTags.filter(t => t !== tag));
    } else {
      setSelectedTags([...selectedTags, tag]);
    }
  };
  
  // 添加自定义标签
  const addCustomTag = () => {
    Alert.alert('功能开发中', '自定义标签功能正在开发中，敬请期待！');
  };
  
  // 显示功能开发中提示
  const showDevelopingAlert = (feature: string) => {
    Alert.alert('功能开发中', `${feature}功能正在开发中，敬请期待！`);
  };
  
  // 提交表单
  const handleSubmit = async () => {
    if (!content.trim()) {
      Alert.alert('内容不能为空', '请输入帖子内容');
      return;
    }
    
    try {
      setIsSubmitting(true);
      
      // 准备表单数据
      const formData = new FormData();
      formData.append('title', content.substring(0, 30)); // 使用内容前30个字符作为标题
      formData.append('content', content);
      
      // 添加标签
      if (selectedTags.length > 0) {
        formData.append('tags', selectedTags.join(','));
      }
      
      // 添加图片
      images.forEach((image, index) => {
        const uri = image.uri;
        const fileType = uri.substring(uri.lastIndexOf('.') + 1);
        const fileName = `image_${index}.${fileType}`;
        
        // @ts-ignore - FormData类型定义问题
        formData.append('files', {
          uri: Platform.OS === 'ios' ? uri.replace('file://', '') : uri,
          name: fileName,
          type: `image/${fileType}`,
        });
      });
      
      // 发送请求
      const response = await createPostWithImages(formData) as unknown as ApiResponse;
      
      if (response && response.code === 0) {
        Alert.alert('发布成功', '帖子已成功发布', [
          {
            text: '确定',
            onPress: () => {
              // 返回首页或跳转到帖子详情
              router.replace(`/post/${response.data}`);
            },
          },
        ]);
      } else {
        Alert.alert('发布失败', response?.message || '请稍后重试');
      }
    } catch (error) {
      console.error('发布帖子出错:', error);
      Alert.alert('发布失败', '请检查网络连接后重试');
    } finally {
      setIsSubmitting(false);
    }
  };
  
  // 取消创建
  const handleCancel = () => {
    router.back();
  };
  
  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <StatusBar style="dark" />
      
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <TouchableOpacity onPress={handleCancel} style={styles.headerButton}>
          <Ionicons name="close" size={24} color="#333" />
        </TouchableOpacity>
        
        <Text style={styles.headerTitle}>发布内容</Text>
        
        <TouchableOpacity 
          onPress={handleSubmit} 
          style={[styles.headerButton, styles.publishButton]}
          disabled={isSubmitting || !content.trim()}
        >
          {isSubmitting ? (
            <ActivityIndicator size="small" color="#fff" />
          ) : (
            <Text style={styles.publishText}>发布</Text>
          )}
        </TouchableOpacity>
      </View>
      
      <ScrollView style={styles.contentContainer}>
        {/* 内容输入区 */}
        <View style={styles.inputContainer}>
          <TextInput
            style={styles.contentInput}
            placeholder="分享你的想法、知识或经验..."
            placeholderTextColor="#999"
            multiline
            value={content}
            onChangeText={setContent}
            maxLength={2000}
          />
        </View>
        
        {/* 图片预览区 */}
        {images.length > 0 && (
          <View style={styles.imagePreviewContainer}>
            {images.map((image, index) => (
              <View key={index} style={styles.imageItem}>
                <Image source={{ uri: image.uri }} style={styles.previewImage} />
                <TouchableOpacity 
                  style={styles.removeImageButton}
                  onPress={() => removeImage(index)}
                >
                  <Ionicons name="close-circle" size={22} color="#fff" />
                </TouchableOpacity>
              </View>
            ))}
            
            {images.length < 9 && (
              <TouchableOpacity style={styles.addImageButton} onPress={pickImage}>
                <Ionicons name="add" size={32} color="#ccc" />
                <Text style={styles.addImageText}>添加图片</Text>
              </TouchableOpacity>
            )}
          </View>
        )}
        
        {/* 图片为空时显示添加按钮 */}
        {images.length === 0 && (
          <TouchableOpacity style={styles.addImageButtonLarge} onPress={pickImage}>
            <Ionicons name="add" size={32} color="#ccc" />
            <Text style={styles.addImageText}>添加图片</Text>
          </TouchableOpacity>
        )}
        
        {/* 标签选择区 */}
        <View style={styles.tagsSection}>
          <Text style={styles.sectionTitle}>选择话题标签</Text>
          <View style={styles.tagsContainer}>
            {TAGS.map((tag) => (
              <TouchableOpacity
                key={tag}
                style={[
                  styles.tagItem,
                  selectedTags.includes(tag) && styles.selectedTagItem,
                ]}
                onPress={() => toggleTag(tag)}
              >
                <Text 
                  style={[
                    styles.tagText,
                    selectedTags.includes(tag) && styles.selectedTagText,
                  ]}
                >
                  {tag}
                </Text>
              </TouchableOpacity>
            ))}
            
            <TouchableOpacity
              style={styles.addTagButton}
              onPress={addCustomTag}
            >
              <Text style={styles.addTagText}>+ 创建</Text>
            </TouchableOpacity>
          </View>
        </View>
        
        {/* 额外功能区 */}
        <View style={styles.extraFeaturesSection}>
          {/* 添加位置 */}
          <TouchableOpacity 
            style={styles.extraFeatureItem}
            onPress={() => showDevelopingAlert('添加位置')}
          >
            <Ionicons name="location-outline" size={22} color="#666" />
            <Text style={styles.extraFeatureText}>添加位置</Text>
            <Ionicons name="chevron-forward" size={20} color="#ccc" style={styles.extraFeatureIcon} />
          </TouchableOpacity>
          
          {/* 提及好友 */}
          <TouchableOpacity 
            style={styles.extraFeatureItem}
            onPress={() => showDevelopingAlert('提及好友')}
          >
            <Ionicons name="people-outline" size={22} color="#666" />
            <Text style={styles.extraFeatureText}>提及好友</Text>
            <Ionicons name="chevron-forward" size={20} color="#ccc" style={styles.extraFeatureIcon} />
          </TouchableOpacity>
          
          {/* 谁可以看到 */}
          <TouchableOpacity 
            style={styles.extraFeatureItem}
            onPress={() => showDevelopingAlert('权限设置')}
          >
            <Ionicons name="eye-outline" size={22} color="#666" />
            <Text style={styles.extraFeatureText}>谁可以看到</Text>
            <View style={styles.visibilityContainer}>
              <Text style={styles.visibilityText}>所有人</Text>
              <Ionicons name="chevron-forward" size={20} color="#ccc" />
            </View>
          </TouchableOpacity>
          
          {/* 评论设置 */}
          <TouchableOpacity 
            style={styles.extraFeatureItem}
            onPress={() => showDevelopingAlert('评论设置')}
          >
            <Ionicons name="chatbubble-outline" size={22} color="#666" />
            <Text style={styles.extraFeatureText}>评论设置</Text>
            <View style={styles.visibilityContainer}>
              <Text style={styles.visibilityText}>允许所有人评论</Text>
              <Ionicons name="chevron-forward" size={20} color="#ccc" />
            </View>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 12,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  headerButton: {
    padding: 6,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  publishButton: {
    backgroundColor: '#1677ff',
    paddingHorizontal: 14,
    paddingVertical: 6,
    borderRadius: 4,
  },
  publishText: {
    color: '#fff',
    fontWeight: '500',
  },
  contentContainer: {
    flex: 1,
  },
  inputContainer: {
    backgroundColor: '#fff',
    padding: 15,
    minHeight: 150,
  },
  contentInput: {
    fontSize: 16,
    color: '#333',
    textAlignVertical: 'top',
    minHeight: 120,
  },
  imagePreviewContainer: {
    backgroundColor: '#fff',
    padding: 10,
    flexDirection: 'row',
    flexWrap: 'wrap',
    borderTopWidth: 1,
    borderTopColor: '#f0f0f0',
  },
  imageItem: {
    width: '30%',
    aspectRatio: 1,
    margin: '1.66%',
    position: 'relative',
  },
  previewImage: {
    width: '100%',
    height: '100%',
    borderRadius: 6,
  },
  removeImageButton: {
    position: 'absolute',
    top: -8,
    right: -8,
    backgroundColor: 'rgba(0,0,0,0.5)',
    borderRadius: 12,
    padding: 1,
  },
  addImageButton: {
    width: '30%',
    aspectRatio: 1,
    margin: '1.66%',
    borderWidth: 1,
    borderStyle: 'dashed',
    borderColor: '#ccc',
    borderRadius: 6,
    justifyContent: 'center',
    alignItems: 'center',
  },
  addImageButtonLarge: {
    backgroundColor: '#fff',
    padding: 20,
    borderTopWidth: 1,
    borderTopColor: '#f0f0f0',
    justifyContent: 'center',
    alignItems: 'center',
  },
  addImageText: {
    color: '#999',
    marginTop: 4,
    fontSize: 12,
  },
  tagsSection: {
    backgroundColor: '#fff',
    padding: 15,
    marginTop: 10,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
    marginBottom: 12,
  },
  tagsContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  tagItem: {
    backgroundColor: '#f0f0f0',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 16,
    marginRight: 8,
    marginBottom: 10,
  },
  selectedTagItem: {
    backgroundColor: '#e6f4ff',
    borderWidth: 1,
    borderColor: '#1677ff',
  },
  tagText: {
    color: '#666',
    fontSize: 14,
  },
  selectedTagText: {
    color: '#1677ff',
  },
  addTagButton: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 16,
    marginRight: 8,
    marginBottom: 10,
    borderWidth: 1,
    borderColor: '#ddd',
    borderStyle: 'dashed',
  },
  addTagText: {
    color: '#999',
    fontSize: 14,
  },
  extraFeaturesSection: {
    backgroundColor: '#fff',
    marginTop: 10,
    marginBottom: 20,
  },
  extraFeatureItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  extraFeatureText: {
    fontSize: 15,
    color: '#333',
    marginLeft: 10,
    flex: 1,
  },
  extraFeatureIcon: {
    marginLeft: 'auto',
  },
  visibilityContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: 'auto',
  },
  visibilityText: {
    fontSize: 14,
    color: '#999',
    marginRight: 4,
  },
}); 